package com.aptech.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
		
	public static final SessionFactory sessionFactory;
	
	static{
		try{
			sessionFactory = new Configuration().configure().buildSessionFactory();
		}catch(Throwable e){
			System.err.println(e.getMessage());
			throw new ExceptionInInitializerError(e);
		}
	}
	
	public static final ThreadLocal session = new ThreadLocal();
	
	public static Session currentSession() throws HibernateException{
		Session currentSession = (Session) session.get();
		
		if(currentSession == null){
			currentSession = sessionFactory.openSession();
			session.set(currentSession);
		}
		
		return currentSession;
	}
	
	public static void closeSession() throws HibernateException{
		Session currentSession = (Session) session.get();
		
		if(currentSession != null){
			currentSession.close();
		}
		
		session.set(null);
	}
	
}
